package tech.springboot.springtasks.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 和AsyncTaskConfig任意开启一个即可
 */
//@Configuration
//@EnableAsync
public class ThreadPoolConfig {

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(50); // 核心线程数
        executor.setMaxPoolSize(200); // 最大线程数
        executor.setQueueCapacity(1000); // 队列容量
        executor.setKeepAliveSeconds(300); // 空闲线程存活时间
        executor.setThreadNamePrefix("local2-executor-"); // 线程名前缀
        executor.setWaitForTasksToCompleteOnShutdown(true); // 等待任务完成再关闭
        executor.setAwaitTerminationSeconds(5); // 强制关闭前的等待时间
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
        executor.setTaskDecorator(new TaskDecorator() {
            @Override
            public Runnable decorate(Runnable runnable) {
                return  () -> {
                    try {
                        runnable.run(); // 执行任务逻辑
                    } finally {
                        // 此处可执行清理 ThreadLocal 缓存
                    }
                };
            }
        });
        executor.initialize();
        return executor;
    }
}